import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {GoodsAddService} from '../goods-add.service';
import {LocalStorageService} from '../../../../lib/service/local-storage.service';
import {EditorComponent} from "../../../../comm-components/wangeditor/editor.component";

import * as _ from 'underscore';
import {AdOssUploadService} from '../../../../lib/service/ad-oss-upload.service';
import {AliyunOssOutputUrl} from '../../../../../config/api';

@Component({
  selector: 'app-edit-manage',
  templateUrl: 'edit.component.html',
  styleUrls: ['edit.component.scss'],
  providers: [GoodsAddService]
})
export class EditComponent implements OnInit {
  codeHelp;
  picHelp;
  otherPicHelp;
  addAttr;
  addGroup;
  addType;
  type;
  message;
  isShow;

  id;
  categoryId; // 当前所选最小分类id
  goodsCategory; // 分类
  goodsAttribute; // 属性集
  appletGoodsCategory; // 分组列表
  appletGoodsCategoryName; // 要添加的分组名称
  appletGoodsCategoryNameStatus = false; // 要添加分组的状态设置

  new_custom = [];
  custom_group = [];  // 自定义规格按照组进行排列
  custom_hasLoading = false;
  nowGoodsAttribute; // 当前选中的属性集
  customize;
  stock = []; // sku stock

  expressTemplateList = [];
  provinceList = [];
  cityList = [];
  regionList = [];

  name;
  price; // 销售价格,千分位 微信价
  retail_Price; // 门市价格,千分位 原价
  in_stock; // 库存
  is_tc = false; // 是否套餐选择项
  goods_number; // 产品编号
  weight;

  first_picture;
  second_picture;
  third_picture;
  fourth_picture;

  limited = false;
  max_buy = 0; // 限购数量,0不限购
  is_free_postage = '包邮'; // 是否包邮 enum('包邮', '不包邮')
  goods_at_province = '';
  goods_at_city = '';
  goods_at_district = '';

  express_template_id; // 关联的运费模板ID
  had_invoice = '无'; // 有无发票 enum('无', '有')
  had_warranty_fix = '无'; // 有无保修 enum('无', '有')
  status = '下架'; // enum('上架', '下架')

  description = '';


  first_picture_file;
  // first_picture;
  second_picture_file;
  // second_picture;
  third_picture_file;
  // third_picture;
  fourth_picture_file;
  // fourth_picture;

  // 文件内容
  f = ['', '', '', ''];
  f_file = ['', '', '', ''];
  // 文件名
  f1 = ['first_picture', 'second_picture', 'third_picture', 'fourth_picture'];
  // 文件后缀
  f1_suffix = ['', '', '', ''];

  AliyunOssOutputUrl;

  editStatus = true;
  norm_mode = '无规格';
  @ViewChild(EditorComponent) editor: EditorComponent;

  constructor(private localStorageService: LocalStorageService,
              private router: Router,
              private route: ActivatedRoute,
              private goodsAddService: GoodsAddService,
              private adOssUploadService: AdOssUploadService) {
    this.getExpressTemplateList();
    this.AliyunOssOutputUrl = AliyunOssOutputUrl;
  }

  ngOnInit() {
    this.editor.changedEitorUsePlace('goods');
    this.route.params.subscribe(params => {
      this.id = params.id;
      this.getAppletGoodsCategory();
      this.goodsAddService.getGoodsInfoById(params.id).subscribe(res => {
        this.categoryId = res.data.goods_category_id||70;
        this.name = res.data.name;
        this.price = res.data.price / 1000;
        this.retail_Price = res.data.retail_price / 1000;
        this.in_stock = res.data.in_stock;
        this.norm_mode = res.data.norm_mode;
        this.goods_number = res.data.goods_number;
        this.weight = res.data.weight;
        if (this.norm_mode === '无规格' && !!this.goods_number) {
          if (this.goods_number.substring(this.goods_number.length - 4) === '@tc@') {
            this.goods_number = this.goods_number.substring(0, this.goods_number.length - 4);
            this.is_tc = true;
          }
        }
        this.max_buy = res.data.max_buy;
        if (this.max_buy <= 0) {
          this.limited = false;
        } else {
          this.limited = true;
        }

        this.is_free_postage = res.data.is_free_postage;

        this.goods_at_province = res.data.goods_at_province;
        this.goods_at_city = res.data.goods_at_city;
        this.goods_at_district = res.data.goods_at_district;

        this.getProvinceList();

        this.express_template_id = res.data.express_template_id;
        this.had_invoice = res.data.had_invoice;
        this.had_warranty_fix = res.data.had_warranty_fix;
        this.description = res.data.description;
        // console.log(res.data.description);
        this.status = res.data.status;
        if (res.data.first_picture) {
          this.f[0] = AliyunOssOutputUrl + '/' + res.data.first_picture + '?' + Math.random();
        }

        if (res.data.second_picture) {
          this.f[1] = AliyunOssOutputUrl + '/' + res.data.second_picture + '?' + Math.random();
        }

        if (res.data.third_picture) {
          this.f[2] = AliyunOssOutputUrl + '/' + res.data.third_picture + '?' + Math.random();
        }

        if (res.data.fourth_picture) {
          this.f[3] = AliyunOssOutputUrl + '/' + res.data.fourth_picture + '?' + Math.random();
        }

        // 类目
        this.getCategoryParent(this.categoryId);
        this.editor.loadingHandle(this.description);

        // 自定义规格
        this.getCustomSku();
      });
    });
  }

  change_attribute_value(ite) {
    ite.bind = !ite.bind;
  }

  getCustomSku() {
    this.goodsAddService.getCustomSkuByGoodsId(this.id).subscribe(res => {
      this.custom_hasLoading = true;
      this.new_custom = res.data;
      if (!!this.goodsAttribute && !!this.goodsAttribute.length) {
        this.doDataMakeTable();
      }
      if (!!this.new_custom.length) {
        this.new_custom.every((val, idx, array) => {
          let data = {};
          if (idx == 0) {
            data["id"] = val.custom_goods_attribute_id;
            data["name"] = val.custom_goods_attribute_name;
            data["goods_category_id"] = val.goods_category_id;
            data["custom_goods_attribute_value"] = [];
            data["custom_goods_attribute_value"].push(val);
            this.custom_group.push(data);
          } else {
            let isNew = false;
            this.custom_group.every((val1, idx1, array1) => {
              if (val1.id === val.custom_goods_attribute_id) {
                val1.custom_goods_attribute_value.push(val);
                isNew = false;
                return false;
              } else {
                isNew = true;
              }
              return true;
            });
            if (isNew) {
              data["id"] = val.custom_goods_attribute_id;
              data["name"] = val.custom_goods_attribute_name;
              data["goods_category_id"] = val.goods_category_id;
              data["custom_goods_attribute_value"] = [];
              data["custom_goods_attribute_value"].push(val);
              this.custom_group.push(data);
            }
          }
          return true;
        });
        // console.log("1");
        // console.log(this.custom_group);
      }
    })
  }

  selectImg($event: any, pic_number) {

    // const files = $event.target.files || $event.dataTransfer.files;
    // console.log($event.path[0].files[0]);
    // console.log($event.path[0].files);
    if ($event.path[0].files[0]) {
      const file = $event.path[0].files[0];

      this.f_file[pic_number] = file;

      switch (pic_number) {
        case 0:
          this.first_picture_file = file;
          break;
        case 1:
          this.second_picture_file = file;
          break;
        case 2:
          this.third_picture_file = file;
          break;
        case 3:
          this.fourth_picture_file = file;
          break;
      }


      const myReader = new FileReader();
      const self = this;
      this.f1_suffix[pic_number] = file.name.replace(/.+\./, '').toLowerCase();
      myReader.readAsDataURL(file);
      myReader.onloadend = function (e) {
        // console.log(myReader.result);
        self.f[pic_number] = myReader.result;
        // console.log(pic_number);
        // console.log(self.f[pic_number]);
      };
    } else {
      this.f[pic_number] = '';
      this.f_file[pic_number] = '';
    }
  }

  uploadImg(product_id) {
    const member_id = this.localStorageService.getNowApplet().user_id;
    const applet_id = this.localStorageService.getNowApplet().id;
    this.adOssUploadService
      .getSignature(`/v1/member/detail/${member_id}/${applet_id}/${product_id}?callback=true`)
      .subscribe(
        res1 => {

          this.f_file.every((val, idx, array) => {
            // 图片名前增加随机数
            const now = new Date();
            const imgName = now.getTime() + this.f1[idx] + '.' + this.f1_suffix[idx];

            if (val) {
              this.adOssUploadService.fileUpload(val, res1.data, imgName, this.f1[idx])
                .subscribe(res2 => {
                    /*if (res2.status === 200) {
                     this.type = 'success';
                     this.message = '保存成功';
                     this.isShow = true;
                     this.localStorageService.setNowApplet(res.data);
                     if (!!turnPage) {
                     this.router.navigate([`/main/store-product/goods-add`]);
                     }
                     } else {
                     this.type = 'error';
                     this.message = '图片上传失败';
                     this.isShow = true;
                     }*/
                  }
                );
            }
            return true;
          });
        }
      );
  }

  // 单选
  changeGoodsAttributeOnly($event, item) {
    const value = Number($event.target.value);
    item.attribute_value.every((val, idx, array) => {
      if (val.id === value) {
        val.bind = true;
      } else {
        val.bind = false;
      }
      return true;
    });
  }

  editGoods() {
    this.description = this.editor.clickHandle();
    if (this.norm_mode == '无规格') {
      if (this.is_tc) {
        this.goods_number += '@tc@';
      }
    } else {
      this.is_tc = false;
      this.stock.every((val, idx, array) => {
        if (val.is_tc) {
          val.isbn += '@tc@';
        }
        return true;
      });
    }
    this.goodsAddService.editGoods(
      this.id,
      this.localStorageService.getNowApplet().applet_uuid,
      this.categoryId, // 分类id
      this.appletGoodsCategory, // 分组
      this.name, // 商品名称
      this.goodsAttribute,
      this.stock,
      this.price,
      this.retail_Price,
      this.in_stock,
      this.goods_number,
      this.weight,
      // this.first_picture,
      // this.second_picture,
      // this.third_picture,
      // this.fourth_picture,
      this.max_buy,
      this.is_free_postage,
      this.goods_at_province,
      this.goods_at_city,
      this.goods_at_district,
      this.express_template_id,
      this.had_invoice,
      this.had_warranty_fix,
      this.status,
      this.description,
      this.norm_mode,
      this.is_tc
    ).subscribe(res => {

      if (res.code === 2000) {
        this.type = 'success';
        this.message = '修改成功';
        this.isShow = true;
        this.ngOnInit();
      } else {
        this.type = 'error';
        this.message = res.message;
        this.isShow = true;
      }
      if (res.data.id) {
        this.uploadImg(res.data.id);
      }
      this.editStatus = true;
    });
  }

  delSku(item) {
    item.selected = false;
    this.doDataMakeTable();
  }

  select_max_buy() {
    if (this.limited === false) {
      this.max_buy = 0;
    } else {
      this.max_buy = null;
    }
  }

  // 根据最小分类id查询到顶级
  getCategoryParent(categoryId) {
    this.goodsAddService.getCategoryParentById(categoryId).subscribe(res => {
      // 分类所属，一维
      this.goodsCategory = res.data.data;
      // 该分类所绑定的 商品集(属性＝＞属性名)
      this.goodsAttribute = res.data.goods_attribute;

      this.goodsAttribute.every((val, idx, array) => {
        // 去除要组合的数据
        val.attribute_value.every((val1, idx1, array1) => {
          val1.goods_attribute_name = val.name;
          return true;
        });

        return true;
      });

      const goods_attribute_set_id_array = [];
      const goods_attribute_set_id_remark_array = [];
      const goods_sku_attribute_value_array = [];
      this.goodsAddService.getGoodsSkuAttributeBindList(this.id).subscribe(rs => {

        if (rs.data.goods_sku_attribute) {
          rs.data.goods_sku_attribute.every((val, idx, array) => {
            goods_attribute_set_id_array.push(val.goods_attribute_set_id);
            goods_attribute_set_id_remark_array.push(val.customize);
            return true;
          });
        }

        if (rs.data.goods_bind_attribute) {
          rs.data.goods_bind_attribute.every((val, idx, array) => {
            goods_sku_attribute_value_array.push(val.goods_attribute_value_id);
            return true;
          });
        }

        // console.log(rs.data);
        // 去重 获取选中的属性集
        // console.log(Array.from(new Set(goods_attribute_set_id_array)));
        this.goodsAttribute.every((val, idx, array) => {
          const index = goods_attribute_set_id_array.indexOf(val.goods_attribute_set_id);
          if (index >= 0) {
            val.selected = true;
            val.remark = goods_attribute_set_id_remark_array[idx];
          }

          val.attribute_value.every((val1, idx1, array1) => {
            const index1 = goods_sku_attribute_value_array.indexOf(val1.id);
            if (index1 >= 0) {
              val1.bind = true;
            } else {
              val1.bind = false;
            }
            return true;
          });

          return true;
        });
        if (this.custom_hasLoading) {
          this.doDataMakeTable();
        }
      });
    });
  }

  // 获取分组
  getAppletGoodsCategory() {
    // console.log(this.localStorageService.getNowApplet().id);
    this.goodsAddService.getAppletGoodsCategory(this.localStorageService.getNowApplet().applet_uuid).subscribe(res => {
      this.appletGoodsCategory = res.data.data;
      this.goodsAddService.getAppletGoodsCategoryRelationBindList(this.id).subscribe(
        rs => {
          this.appletGoodsCategory.every((val, idx, array) => {
            rs.data.every((val1, idx1, array1) => {
              if (val.id === val1.applet_goods_category_id) {
                val.bind = true;
              }
              return true;
            })
            ;
            return true;
          });
        }
      );

    });
  }

  // 添加分组
  addAppletGoodsCategory() {
    this.appletGoodsCategoryNameStatus = true;
    const applet_uuid = this.localStorageService.getNowApplet().applet_uuid;
    if (this.appletGoodsCategoryName) {
      this.goodsAddService.addAppletGoodsCategory(this.appletGoodsCategoryName, applet_uuid).subscribe(
        rs => {
          if (rs.code === 2000) {
            this.appletGoodsCategoryName = null;
            this.getAppletGoodsCategory();
          }
          this.appletGoodsCategoryNameStatus = false;
          // re get
        }
      );
    }
  }

  // 选择属性名
  selectGoodsAttribute($event) {
    const goods_attribute_set_id = Number($event.target.value);
    if (goods_attribute_set_id === 0) {
      this.nowGoodsAttribute = null;
    }
    this.goodsAttribute.every((val, idx, array) => {
      if (val.goods_attribute_set_id === goods_attribute_set_id) {
        this.nowGoodsAttribute = val;
        // val.selected = true;
      }
      return true;
    });
  }


  /*selectGoodsAttributeValue($event) {
   const id = Number($event.target.value);
   if (id === 0) {
   this.nowGoodsAttributeValueId = null;
   } else {
   this.nowGoodsAttributeValueId = id;
   }
   console.log(id);
   }*/

  addGoodsAttribute() {
    this.goodsAttribute.every((val, idx, array) => {
      // console.log(val.goods_attribute_set_id === this.nowGoodsAttribute.goods_attribute_set_id);
      if (val.goods_attribute_set_id === this.nowGoodsAttribute.goods_attribute_set_id) {
        val.selected = true;
        val.remark = this.customize;
      }
      if (val.attribute_value.length <= 0) {
        val.selected = false;
      } else {
        let c = 0;
        val.attribute_value.every((val1, idx1, array1) => {
          if (val1.bind === true) {
            // val1.goods_attribute_set_id = val.goods_attribute_set_id;
            c++;
          }
          return true;
        });
        if (c === 0) {
          val.selected = false;
        }
      }

      return true;
    });
    this.doDataMakeTable();

  }

  changeGoodsAttribute() {
    this.goodsAttribute.every((val, idx, array) => {
      // console.log(val.goods_attribute_set_id === this.nowGoodsAttribute.goods_attribute_set_id);
      if (val.attribute_value.length <= 0) {
        val.selected = false;
      } else {
        let c = 0;
        val.attribute_value.every((val1, idx1, array1) => {
          if (val1.bind === true) {
            c++;
          }
          return true;
        });
        if (c === 0) {
          val.selected = false;
        }
      }
      return true;
    });
    this.doDataMakeTable();
  }

  // 处理
  doDataMakeTable() {
    // const data = [];
    // if (!!this.goodsAttribute.length) {
    //   this.goodsAttribute.every((val, idx, array) => {
    //     // 去除要组合的数据
    //     if (val.selected === true) {
    //       const attribute_value_array = [];
    //       val.attribute_value.every((val1, idx1, array1) => {
    //         if (val1.bind === true) {
    //           val1.goods_attribute_set_id = val.goods_attribute_set_id;
    //           val1.goods_attribute_set_remark = val.remark;
    //           // val1.goods_attribute_set_attribute_id = val.id;
    //           attribute_value_array.push(val1);
    //         }
    //         return true;
    //       });
    //       data.push(attribute_value_array);
    //     }
    //     return true;
    //   });
    // }
    //
    // if (!!this.new_custom.length) {
    //   this.new_custom.every((val, idx, array) => {
    //     let canAdd = false;
    //     if (!!data.length) {
    //       data[0].every((val1, idx1, array1) => {
    //         if (val1.custom_goods_attribute_id == val.custom_goods_attribute_id) {
    //           canAdd = false;
    //           return false;
    //         } else {
    //           canAdd = true;
    //           return true;
    //         }
    //       });
    //       if (canAdd) {
    //         val.goods_attribute_set_id = val.custom_goods_attribute_id;
    //         val.goods_attribute_id = val.id;
    //         // attribute_value_array.push(val);
    //         data[0].push(val);
    //       }
    //     } else {
    //       val.goods_attribute_set_id = val.custom_goods_attribute_id;
    //       val.goods_attribute_id = val.id;
    //       data.push([]);
    //       data[0].push(val);
    //     }
    //
    //     return true;
    //   });
    //
    // }
    //
    // const stock = this.doExchange(data);
    // if (stock) {
    //   this.stock = [];
    //   stock.every((val, idx, array) => {
    //     this.stock[idx] = {sku: []};
    //     // this.stock[idx].sku = [];
    //     if (val.id) {
    //       this.stock[idx].sku.push(val);
    //     } else {
    //       this.stock[idx].sku = val;
    //     }
    //     return true;
    //   });
    //
    //   this.stock.every((val2, idx2, array2) => {
    //     val2.sku_array = [];
    //     val2.sku.every((val22, idx22, array22) => {
    //       val2.sku_array.push({
    //         goods_attribute_id: val22.goods_attribute_id,
    //         goods_attribute_set_id: val22.goods_attribute_set_id,
    //         goods_attribute_value_id: val22.id
    //       });
    //       return true;
    //     });
    //     return true;
    //   });
    //
    // } else {
    //   this.stock = [];
    // }

    this.goodsAddService.getGoodsSkubindList(this.id).subscribe(
      res => {
        this.stock = [];
        const temp = res.data;
        temp.every((val, idx, array) => {
          let data = {},
            sku_info = JSON.parse(val.sku_info);
          data["sku"] = [];
          if (!!sku_info.sku.length) {
            sku_info.sku.every((val1, idx2, array) => {
              val1.value = val1.goods_sku_attribute_value_name;
              data["sku"].push(val1);
              return true;
            })
          }
          if (!!sku_info.sku2 && !!sku_info.sku2.length) {
            sku_info.sku2.every((val1, idx2, array) => {
              val1.value = val1.goods_sku_attribute_value_name;
              val1.goods_attribute_set_id = val1.custom_goods_attribute_id;
              data["sku"].push(val1);
              return true;
            })
          }
          data["price"] = val.price / 1000;
          data["retail_Price"] = val.retail_Price / 1000;
          data["in_stock"] = val.in_stock;
          if (!!val.isbn) {
            if (val.isbn.substring(val.isbn.length - 4) == '@tc@') {
              val.isbn = val.isbn.substring(0, val.isbn.length - 4);
              data["is_tc"] = true;
            } else {
              data["is_tc"] = false;
            }
          }
          data["isbn"] = val.isbn;
          this.stock.push(data);
          return true;
        });
        console.log(this.stock);
        // temp.every((val, idx, array) => {
        //   // let temp1;
        //   val.other.every((val1, idx1, array1) => {
        //     delete val1.created_at;
        //     delete val1.updated_at;
        //     delete val1.deleted_at;
        //     delete val1.customize;
        //     delete val1.created_at;
        //     delete val1.goods_id;
        //     delete val1.goods_sku_id;
        //     delete val1.id;
        //     return true;
        //   });
        //   return true;
        // });

        // this.stock.every((val2, idx2, array2) => {
        //   temp.every((val, idx, array) => {
        //     if (_.isEqual(val2.sku_array, val.other)) {
        //       val2.in_stock = val.in_stock;
        //       val2.price = val.price / 1000;
        //       val2.retail_Price = val.retail_Price / 1000;
        //       val2.isbn = val.isbn;
        //     }
        //     return true;
        //   });
        //   return true;
        // });
      }
    );

  }


  // 组合
  doExchange(arr) {
    const len = arr.length;
    // 当数组大于等于2个的时候
    if (len >= 2) {
      // 第一个数组的长度
      const len1 = arr[0].length;
      // 第二个数组的长度
      const len2 = arr[1].length;
      // 2个数组产生的组合数
      const lenBoth = len1 * len2;
      //  申明一个新数组
      const items = new Array(lenBoth);
      // 申明新数组的索引
      let index = 0;
      for (let i = 0; i < len1; i++) {
        for (let j = 0; j < len2; j++) {
          if (arr[0][i] instanceof Array) {
            items[index] = arr[0][i].concat(arr[1][j]);
          } else {
            items[index] = [arr[0][i]].concat(arr[1][j]);
          }
          index++;
        }
      }
      const newArr = new Array(len - 1);
      for (let i = 2; i < arr.length; i++) {
        newArr[i - 1] = arr[i];
      }
      newArr[0] = items;
      return this.doExchange(newArr);
    } else {
      return arr[0];
    }
  }

  getExpressTemplateList() {
    this.goodsAddService.getExpressTemplateList(this.localStorageService.getNowApplet().applet_uuid).subscribe(res => {
      this.expressTemplateList = res.data.data;
    });
  }

  selectExpressTemplate($event) {
    this.express_template_id = $event.target.value;
  }

  getProvinceList() {
    this.provinceList = [];
    this.cityList = [];
    this.regionList = [];
    this.goodsAddService.getProvinceList().subscribe(res => {
      if (res.data) {
        this.provinceList = res.data;

        this.goodsAddService.getCityList(this.goods_at_province).subscribe(res1 => {
          // console.log(res);
          if (res1.data) {
            this.cityList = res1.data;
            this.goodsAddService.getRegionList(this.goods_at_city).subscribe(res2 => {
              // console.log(res);
              if (res2.data) {
                this.regionList = res2.data;
              }
            });
          }
        });

      }
    });
  }

  selectProvince($event) {
    this.cityList = [];
    this.regionList = [];
    const province_id = $event.target.value;
    if (!province_id) {
      return;
    }
    this.goodsAddService.getCityList(province_id).subscribe(res => {
      // console.log(res);
      if (res.data) {
        this.cityList = res.data;
      }
    });
  }

  selectCity($event) {
    this.regionList = [];
    const city_id = $event.target.value;
    if (!city_id) {
      return;
    }
    this.goodsAddService.getRegionList(city_id).subscribe(res => {
      // console.log(res);
      if (res.data) {
        this.regionList = res.data;
      }
    });
  }

  /*closeModal() {
   }


   /!*自定义添加
   1: 品牌
   *!/
   addItem(type: number) {
   switch (type) {
   case 1:
   if (this.brand == -1) {
   this.addAttr = 2;
   }
   break;
   }
   }

   // 确认添加自定义
   confirmAddItem() {
   this.isShow = true;
   this.message = '添加品牌类目成功';
   }

   promptIsShow(event: any): void {
   this.isShow = event;
   }*/

  promptIsShow(event: any): void {
    this.isShow = event;
  }

  //wangEdit编辑器
  PostData(event): void {
    //console.log(event);
  }
}
